package com.thenie.chat.rabbitmq;

import com.thenie.chat.config.RabbitmqConfig;
import com.thenie.chat.service.IFriendService;
import com.thenie.chat.util.WebSocketUtil;
import com.thenie.chat.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import static com.thenie.chat.controller.DialogSocketHandler.SESSION_MAP;

@Component
@Slf4j
public class OnlineConsumer {


    @Autowired
    private IFriendService friendService;

    /**
     * 发送好友已上线通知
     * @param onlineDownId 上线用户id
     * @throws IOException
     */
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_ONLINE_UP})
    public void sendOnlineUp(Long onlineDownId) throws IOException {
        //获取好友列表(根据在线排序)
        List<UserInfoVo> list = friendService.findMyFriendListOrderByOnLine(onlineDownId);
        Iterator<UserInfoVo> iterator = list.iterator();
        //遍历列表，若好友在线发送通知
        while(iterator.hasNext()){
            UserInfoVo userInfoVo = iterator.next();
            Integer onLine = userInfoVo.getOnLine();
            if (onLine!=null && onLine.equals(1)){
                WebSocketSession webSocketSession = SESSION_MAP.get(userInfoVo.getId().toString());
                if (webSocketSession != null){
                    WebSocketUtil.sendOnlineUpMsg(webSocketSession,onlineDownId);
                }
            }
            if (onLine!=null && onLine.equals(0)){//因排序关系，遇到第一个不在线的就可以退出
                break;
            }
        }
    }

    /**
     * 发送好友已下线通知
     * @param onlineDownId 下线用户id
     * @throws IOException
     */
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_ONLINE_DOWN})
    public void sendOnlineDown(Long onlineDownId) throws IOException {
        //获取好友列表(根据在线排序)
        List<UserInfoVo> list = friendService.findMyFriendListOrderByOnLine(onlineDownId);
        Iterator<UserInfoVo> iterator = list.iterator();
        //遍历列表，若好友在线发送通知
        while(iterator.hasNext()){
            UserInfoVo userInfoVo = iterator.next();
            Integer onLine = userInfoVo.getOnLine();
            if (onLine!=null && onLine.equals(1)){
                WebSocketSession webSocketSession = SESSION_MAP.get(userInfoVo.getId().toString());
                if (webSocketSession != null){
                    WebSocketUtil.sendOnlineDownMsg(webSocketSession,onlineDownId);
                }
            }
            if (onLine!=null && onLine.equals(0)){//因排序关系，遇到第一个不在线的就可以退出
                break;
            }
        }
    }
}
